<!-- 机构管理 -->
<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { sysOrgDataList, sysOrgSaveOrUpdate, sysOrgDeleteById } from '@/api/backstage'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag } from 'element-plus'
import { Icon } from '@/components/Icon'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import { Write, Detail, orgTypeData } from './components'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { cloneDeep } from 'lodash-es'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await sysOrgDataList(searchParams.value)
    return {
      list: cgTree(res.data, null) || []
    }
  },
  fetchDelApi: async () => {
    const res = await sysOrgDeleteById({ id: delId.value })
    return !!res
  }
})

//将树结构加一个属性parent字段，方便后续操作
const cgTree = (data, parent) => {
  if (parent) {
    delete parent.children
    delete parent.parent
  }
  for (let i = 0; i < data.length; i++) {
    data[i].parent = parent
    if (data[i].children && data[i].children.length > 0) {
      cgTree(data[i].children, cloneDeep(data[i]))
    }
  }
  return data
}

const { dataList, loading } = tableState

const { getList, delList } = tableMethods
const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: '机构名称'
  },
  {
    field: 'orgType',
    label: '机构类型',
    width: 120,
    slots: {
      default: (data: any) => {
        const val = orgTypeData.find((item) => item.value === data.row.orgType)?.label
        return <>{val}</>
      }
    }
  },
  {
    field: 'shortname',
    label: '机构简称'
  },
  {
    field: 'legal',
    label: '机构法人',
    width: 150
  },
  {
    field: 'telephone',
    label: '法人联系方式',
    width: 150
  },
  {
    field: 'sortOrder',
    label: '显示排序',
    width: 100
  },
  {
    field: 'createTime',
    label: '创建时间',
    width: 180
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" link onClick={() => AddAction(row)}>
              新增
            </BaseButton>
            <BaseButton type="primary" link onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="success" link onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton type="danger" link disabled={!row.parentId} onClick={() => delData(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const delLoading = ref(false)
const delId = ref('')
const delData = async (row?: any) => {
  delId.value = row.id

  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}

const searchParams = ref({
  name: '',
  status: null
})

const initValue = (Expose) => {
  Expose.setValues(searchParams.value)
}

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '机构名称',
    component: 'Input'
  },
  {
    field: 'orgType',
    label: '机构类型',
    component: 'Select',
    componentProps: {
      options: orgTypeData,
      clearable: true
    }
  }
])
const searchRef = ref<ComponentRef<typeof Search>>()

const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

/** 搜索栏重置 */
const resetSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = (row: any) => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = { parentId: row.id, parent: { name: row.name } }
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log(formData)
  if (formData) {
    delete formData.parent
    delete formData.children
    saveLoading.value = true
    await sysOrgSaveOrUpdate(formData)
    getList()
    saveLoading.value = false
    dialogVisible.value = false
  }
}
</script>

<template>
  <ContentWrap class="flex-1">
    <Search
      ref="searchRef"
      :schema="searchSchema"
      @register="initValue"
      @reset="resetSearchParams"
      @search="setSearchParams"
    />
    <Table
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :search-params="searchParams"
    />

    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
